from flask import Flask, render_template, request, jsonify
from datetime import datetime

app = Flask(__name__)

# 模拟用户数据
users = [
    {"id": 1, "username": "张三", "age": 28, "occupation": "工程师", "created_at": "2023-01-15", "status": "活跃"},
    {"id": 2, "username": "李四", "age": 32, "occupation": "设计师", "created_at": "2023-02-20", "status": "活跃"},
    {"id": 3, "username": "王五", "age": 25, "occupation": "产品经理", "created_at": "2023-03-10", "status": "不活跃"},
    {"id": 4, "username": "赵六", "age": 35, "occupation": "工程师", "created_at": "2023-01-08", "status": "活跃"},
    {"id": 5, "username": "钱七", "age": 29, "occupation": "运营", "created_at": "2023-04-05", "status": "活跃"},
    {"id": 6, "username": "孙八", "age": 31, "occupation": "设计师", "created_at": "2023-02-28", "status": "不活跃"},
    {"id": 7, "username": "周九", "age": 27, "occupation": "工程师", "created_at": "2023-03-22", "status": "活跃"},
    {"id": 8, "username": "吴十", "age": 33, "occupation": "产品经理", "created_at": "2023-01-30", "status": "不活跃"},
    {"id": 9, "username": "郑十一", "age": 26, "occupation": "运营", "created_at": "2023-05-12", "status": "活跃"},
    {"id": 10, "username": "王十二", "age": 34, "occupation": "工程师", "created_at": "2023-04-18", "status": "活跃"},
]

@app.route('/')
def index():
    return render_template('index.html', users=users)

@app.route('/search')
def search():
    username_query = request.args.get('username', '').strip().lower()
    date_query = request.args.get('date', '').strip()
    
    results = users
    
    # 按用户名搜索
    if username_query:
        results = [user for user in results if username_query in user['username'].lower()]
    
    # 按创建时间搜索
    if date_query:
        try:
            # 将查询日期转换为datetime对象
            search_date = datetime.strptime(date_query, '%Y-%m-%d').date()
            filtered_results = []
            
            for user in results:
                # 将用户创建时间转换为datetime对象
                user_date = datetime.strptime(user['created_at'], '%Y-%m-%d').date()
                if user_date == search_date:
                    filtered_results.append(user)
            
            results = filtered_results
        except ValueError:
            # 日期格式错误，忽略日期筛选
            pass
    
    return jsonify({'users': results, 'count': len(results)})

if __name__ == '__main__':
    app.run(debug=True)